#include "logger.h"

Logger::Logger()
{

}

QFile *Logger::logFile = nullptr;
QTextStream *Logger::logStream = nullptr;
QMutex *Logger::mutex = new QMutex();
QString Logger::filePath;

void Logger::initialize(const QString &filePath) {
    Logger::filePath = filePath;
    logFile = new QFile(filePath);
    if (!logFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        qDebug() << "无法打开日志文件进行写入：" << filePath;
        return;
    }
    logStream = new QTextStream(logFile);
    qDebug()<<"日志启动";
}

void Logger::finalize() {
    if (logFile && logFile->isOpen()) {
        logFile->close();
        delete logFile;
        logFile = nullptr;
    }
    if (logStream) {
        delete logStream;
        logStream = nullptr;
    }
    delete mutex;
    mutex = nullptr;
    qDebug()<<"退出日志记录";
}

void Logger::logMessage(QString level, const QString &message) {
    if (!logFile || !logFile->isOpen()) {
        return;
    }

    QMutexLocker locker(mutex);
    QString formattedMessage = QString("[%1] %2").arg(level).arg(message);
    *logStream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz ") << formattedMessage << endl;
}

void Logger::clearLogFile() {
    if (logFile && logFile->isOpen()) {
        logFile->close();
    }
    QFile::remove(filePath); // 删除现有的日志文件
    logFile = new QFile(filePath);
    if (!logFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        qDebug() << "无法重新创建日志文件进行写入：" << filePath;
        return;
    }
    logStream = new QTextStream(logFile);
}
